package quotation.utils;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import quotation.exception.BusinessException;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * jwt工具类
 *
 * @author tuc
 */
public class JwtUtil {

    /**
     * 加密秘钥
     */
    private static final String SECRET = "G2Ccxs4StFxSyAs64JjHwahi7MYkXM0H";


    /**
     * 生成token
     *
     * @param userId
     * @return String
     */
    public static String generateToken(Long userId, Integer type, String accountName) {
        Map<String, Object> claims = new HashMap<>(4);
        claims.put("userId", userId);
        claims.put("type", type);
        claims.put("accountName", accountName);
        return generateToken(claims);
    }

    public static String generateTokenByOpenId(String openId, Integer type, String accountName) {
        Map<String, Object> claims = new HashMap<>(4);
        claims.put("userId", openId);
        claims.put("type", type);
        claims.put("accountName", accountName);
        return generateToken(claims);
    }

    /**
     * 生成token
     *
     * @param claims
     * @return String
     */
    private static String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                //.setExpiration(generateExpirationDate())
                .setIssuedAt(generateCurrentDate())
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
    }

    private static Date generateCurrentDate() {
        return new Date(System.currentTimeMillis());
    }


    private static Date generateExpirationDate() {
        /**
         * 有效时间(当前设置30天)
         */
        long expiration = (long) 30 * 24 * 60 * 60 * 1000;
        return new Date(System.currentTimeMillis() + expiration);
    }


    /**
     * 获取用户编号
     *
     * @param token
     * @return Integer
     */
    public static Claims getClaims(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            throw new BusinessException("无效的token");
        }
    }
}